package progress.exa37.loader;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MyClassLoader extends ClassLoader {

    /**
     * 根据路径和类全名对字节码文件进行读取并加载
     * @param pathName 字节码文件路径 file:///E:/Personal/MyRepository/study/Java基础学习/src/main/java/Progress/exa37/complier/Test.class
     * @return 返回这个类的Class对象
     */
    @Override
    protected Class<?> findClass(String pathName)  throws ClassFormatError {
        // 声明字节码数组
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(new URI(pathName));
            // 读取字节码文件的字节码
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
        String className = pathName.substring(pathName.indexOf("java")+5,pathName.indexOf(".class")).replace("/",".");
        // 根据类的包名，字节码数组构建class对象
        Class<?> clazz = defineClass(className, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }


}
